package javabase.clone;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;

/**
 * <pre>
 *   Title: DeepClone.java
 *   Description: 深度克隆
 *   Copyright: yundaex.com Copyright (c) 2013
 *   Company: 上海韵达货运有限公司
 * </pre>
 * 
 * @author liuzhaoqing
 * @version 1.0
 * @date 2014年10月16日
 */
class Person implements Serializable, Cloneable {

	private static final long serialVersionUID = 1L;
	
	private int no;
	private String name;
	private String[] schools;
	
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String[] getSchools() {
		return schools;
	}
	public void setSchools(String[] schools) {
		this.schools = schools;
	}
	
	@Override
	public String toString() {
		return "Person [no=" + no + ", name=" + name + ", schools=" + Arrays.toString(schools) + "]";
	}
	
	@Override
	public Object clone() {
		Person dc = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(baos);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			oos.writeObject(this);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			oos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
		ObjectInputStream bis = null;
		try {
			bis = new ObjectInputStream(bais);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			dc = (Person)bis.readObject();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return dc;
	}
}
public class DeepClone {

	public static void main(String[] args) {
		Person person = new Person();
		person.setNo(1);
		person.setName("lzq");
		person.setSchools(new String[]{"xiaoxue","chuzhong"});
		
		System.out.println("克隆前：" + person);
		
		Person person2 = (Person)person.clone();
		person2.setNo(222);
		person2.setName("lzq222");
		person2.setSchools(new String[]{"xiaoxue222","chuzhong222"});
		System.out.println("克隆后：" + person2);
	}

}
